package upload

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/net/ghttp"
	"os"
	"path/filepath"
	"server/internal/consts"
	"server/internal/model"
	"server/internal/service"
	"strings"
)

type LocalUpload struct {
}

func (L *LocalUpload) UploadFile(ctx context.Context, file *ghttp.UploadFile, fileSubject string) (out model.FileUploadOutput, err error) {
	out = model.FileUploadOutput{}
	// 生成文件绝对路径
	absolutePath := GenerateUploadFilePath(ctx, "", consts.FileUploadStorageTypeLocal, fileSubject) // 文件名传空，只会生成目录
	// 文件保存至本地
	filename, err := file.Save(absolutePath, true)
	if err != nil {
		return
	}
	// 拼接目录和文件名得到完整的文件路径-绝对路径
	out.AbsolutePath = filepath.ToSlash(filepath.Join(absolutePath, filename))

	// 相对路径
	config, err := service.File().GetFileUploadConfig(ctx)
	if err != nil {
		return
	}

	// 获取存储数据库中相对路径
	fileServerDIR := strings.TrimPrefix(filepath.ToSlash(config.Local.FileServerDIR), "./")
	out.RelativePath = filepath.ToSlash(strings.TrimPrefix(out.AbsolutePath, fileServerDIR)) // 去掉文件服务存储路径
	out.RelativePath = strings.TrimPrefix(out.RelativePath, "/")

	// 文件可访问的URL
	out.URL = FormatUploadFileURL(ctx, out.RelativePath, consts.FileUploadStorageTypeLocal)
	fmt.Println(out.URL)
	return
}

func (L *LocalUpload) DeleteFile(ctx context.Context, key string) (err error) {
	if len(key) == 0 {
		return gerror.New("文件key不能为空")
	}
	// 获取配置
	config, err := service.File().GetFileUploadConfig(ctx)
	if err != nil {
		return
	}
	//生成文件的绝对路径
	absolutePath := filepath.ToSlash(filepath.Join(config.Local.FileServerDIR, key))

	if fileInfo, err := os.Stat(absolutePath); os.IsNotExist(err) {
		err = gerror.New("文件不存在")
		return err
	} else if fileInfo.IsDir() {
		err = gerror.New("不能删除目录")
		return err
	}
	// 删除文件
	err = os.Remove(absolutePath)
	if err != nil {
		return
	}
	return nil
}
